package com.axter.chrome.ui;

import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextField;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Window;

import java.io.File;

/**
 * Created by zhaobo on 2017/8/2.
 */
public class SomeEvent {
    public static void DragDrop(DragEvent event, TextField tf_ago) {
        Dragboard dragboard = event.getDragboard();
        if (event.isAccepted()) {
            File file = dragboard.getFiles().get(0); //获取拖入的文件
            tf_ago.setText(file.getAbsolutePath());
        }
    }

    public static void DragOver(DragEvent event, String format) {
        Dragboard dragboard = event.getDragboard();
        if (dragboard.hasFiles()) {
            File file = dragboard.getFiles().get(0);
            if (file.getAbsolutePath().endsWith("." + format)) { //用来过滤拖入类型
                event.acceptTransferModes(TransferMode.LINK);//接受拖入文件
            }
        }
    }

    private static File savedDir;

    public static void openFile(Window window, TextField tf_ago, String title, String format) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle(title);
        if (savedDir != null && savedDir.exists()) {
            fileChooser.setInitialDirectory(savedDir);
        }
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter(format, "*." + format)
        );
        File file = fileChooser.showOpenDialog(window);
        if (file != null && file.exists()) {
            savedDir = file.getParentFile();
            tf_ago.setText(file.getAbsolutePath());
        }
    }

    public static Alert createAlert(Window stage, String msg) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION, "");
        alert.initModality(Modality.APPLICATION_MODAL);
        alert.initOwner(stage);
        alert.getDialogPane().setContentText(msg);
        alert.getDialogPane().setHeaderText(null);
        alert.showAndWait()
                .filter(response -> response == ButtonType.OK)
                .ifPresent(response -> System.out.println("The alert was approved"));
        return alert;
    }
}
